/**
 * LCR 181. 字符串中的单词反转
 * https://leetcode.cn/problems/fan-zhuan-dan-ci-shun-xu-lcof/description/
 */
class Solution {
    public String reverseMessage(String message) {
        String[] str = message.trim().split(" ");
        StringBuilder ret = new StringBuilder();
        for(int i = str.length - 1; i >= 0; i--) {
            if(str[i].equals("")) continue;
            ret.append(str[i] + " ");
        }
        return ret.toString().trim();
    }

    public String reverseMessage2(String message) {
        message = message.trim();
        char[] ch = message.toCharArray();
        int end = ch.length - 1, start = ch.length - 1;
        StringBuilder ret = new StringBuilder();

        while(start >= 0) {
            while(start >= 0 && ch[start] != ' ') start--;
            String tmp = message.substring(start + 1, end + 1);
            ret.append(tmp + ' ');
            while(start >= 0 && ch[start] == ' ') start--;
            end = start;
        }

        return ret.toString().trim();
    }
}